﻿using UnityEngine;
using System.Collections;

public class BuildingSynchronization : MonoBehaviour {

    public int ownerX = 0;
    public int ownerY = 0;

    VisualSideBoardManager boardManager = null;

	// Use this for initialization
	void Start () {

        boardManager = GameObject.Find("TopManager").transform.FindChild("VisualBoard").GetComponent<VisualSideBoardManager>();

	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
    {
        if (stream.isWriting)
        {
            Vector3 position = transform.position;
            stream.Serialize(ref position);

            stream.Serialize(ref ownerX);
            stream.Serialize(ref ownerY);
        }
        else
        {
            Vector3 position = transform.position;
            stream.Serialize(ref position);
            transform.position = position;

            int newOwnerX = ownerX;
            int newOwnerY = ownerY;
            stream.Serialize(ref newOwnerX);
            stream.Serialize(ref newOwnerY);

            if (ownerX != newOwnerX || ownerY != newOwnerY)
            {
                AssignParent(ownerX, ownerY);
            }
        }
    }

    void AssignParent(int x, int y)
    {
        this.transform.parent = boardManager.myBoard[x, y].transform;
    }
}
